package com.hlkj.action.fileupload;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.hlkj.tool.form.FormRead;
import com.hlkj.tool.form.UploadFile;
import com.hlkj.tool.results.JsonBulid;
import com.hlkj.tool.results.ResultParameters;
import com.hlkj.util.SQLFactory;

public class FileUploadAction {

	public String getOneUploadFileInputStream() {
		JsonBulid jsonBulid = null;
		FormRead formRead = new FormRead();
		// UploadFile uploadFile = formRead.getParamFile("ImageWaterIo");
		UploadFile[] uploadFiles = formRead.getParamFiles("ImageWaterIo");

		try {
			for (UploadFile uploadFile : uploadFiles) {
				String img_path = uploadPhoto(uploadFile);
				String sql = "INSERT INTO publish_info ( title, content, send_id, send_time, file_path ) VALUES ( '测试', '测试测试', 1, '2013-9-18 14:16:42',?)";
				int count = SQLFactory.update(sql, img_path);
				if (count == -1) {
					jsonBulid = JsonBulid.success(false).msg("上传失败!");
					ResultParameters.setJson(jsonBulid.json());
					return ResultParameters.JSON;
				}
			}
			jsonBulid = JsonBulid.success(true).msg("上传成功!");
		} catch (IOException e) {
			e.printStackTrace();
			jsonBulid = JsonBulid.success(false).msg("上传失败!");
		} finally {

		}

		ResultParameters.setJson(jsonBulid.json());
		return ResultParameters.JSON;
	}

	public String uploadPhoto(UploadFile uploadFile) throws IOException {

		String path = ServletActionContext.getServletContext().getRealPath(
				"/images");
		File corp_img = uploadFile.getFile();
		String fileName = uploadFile.getFileName();
		fileName = getNewFileName(fileName);

		File savefile = new File(new File(path), fileName);
		if (!savefile.getParentFile().exists())
			savefile.getParentFile().mkdirs();
		FileUtils.copyFile(corp_img, savefile);

		String img_path = ServletActionContext.getServletContext()
				.getContextPath()
				+ File.separator + "images" + File.separator + fileName;

		// String saveFileUrl = String.format(path, fileName);
		// corp_img.renameTo(new File(saveFileUrl));
		return img_path;
	}

	/**
	 * 文件重命名
	 * 
	 * @Title: getNewFileName
	 * @param fileName
	 * @return String
	 */
	public String getNewFileName(String fileName) {
		int mid = fileName.lastIndexOf(".");
		String ext = fileName.substring(mid + 1, fileName.length());
		UUID uuid = UUID.randomUUID();
		String newFileName = uuid.toString() + "." + ext;
		return newFileName;
	}
}
